<?php
namespace App\Http\Controllers\Chanjet;

use App\Admin\Models\Account;
use App\Http\Controllers\BaseController as CommonBase;
use App\Models\Chanjet\TplusAccount;
use App\Models\Chanjet\TplusToken;
use App\Services\Chanjet\ChanjetRequest;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
use Maatwebsite\Excel\Facades\Excel;

class BaseController extends CommonBase
{
    /**
     *  检查目标查询结果是否有缓存
     *
    */
    public function checkReportCache($data){
        if(empty($data["controllerName"]) || empty($data["condition"])){
            return ['code'=>'001','msg'=>'请求参数异常'];
        }
        $controllerName = $data["controllerName"];
        $start_cache_time = strtotime("-1 hour");
        $end_cache_time = time();
        //查询12h之内是否查询过
        $cache = \App\Models\Chanjet\TplusReportDataCache::where(['paramDic'=>json_encode($data["condition"]),'business_type'=>$controllerName,'cpid'=>$this->mangerinfo['cpid']])->whereBetween('paramTime',[$start_cache_time,$end_cache_time])->first();
        $cache = '';
        if($cache){
            return ['code'=>'000','data' => json_decode($cache['response'],true)];
        }else{
            //重新触发查询
            $res = $this->setDataCache($data);
            return $res;
        }

    }
    /**
     *  设置缓存
     *
    */
    public function setDataCache($data=[],$res=[]){
        $searchItem = array_filter($data["condition"],function($item){
            if($item[0] != 'cpid') return true;
        });

        $common = new TplusCommonController();
        $res = $common->getExternalData($data['controllerName'],$data['org_id'],$searchItem,'',true);
        $responseData = is_string($res) ? json_decode($res, true) : $res;

        if (is_array($responseData) && array_key_exists('code', $responseData) && $responseData['code'] === '000') {
            $this->clearDataCacheAndInsert($data, $responseData);
        }
        return $responseData;
    }
    /**
     *  清理报表缓存
     *
    */
    public function clearDataCacheAndInsert($data=[],$res=[]){
        $reportDataCache = \App\Models\Chanjet\TplusReportDataCache::where(['paramDic'=>json_encode($data['condition']),'business_type'=>$data["controllerName"],'cpid'=>$this->mangerinfo['cpid']])->first();
        $insert_data = [
            "cpid" => $this->mangerinfo['cpid'],
            "paramDic" => json_encode($data["condition"]),
            "business_type" => $data["controllerName"],
            "paramTime" => time(),
            "response" => json_encode($res['data'])
        ];
        if(!$reportDataCache){
            \App\Models\Chanjet\TplusReportDataCache::create($insert_data);
        }else{
            $ids = json_decode($reportDataCache['response'],true);
            $businessModel = self::getFullPath($data["controllerName"]);

            $businessModel::whereIn('id',$ids)->delete();
            $reportDataCache->delete();
            \App\Models\Chanjet\TplusReportDataCache::create($insert_data);
        }
        return true;
    }
    public static function getFullPath($name = "",$ident ='m'){
        if($ident == 'c'){
            return "\\App\\Http\\Controllers\\Chanjet\\" . $name;
        }
        if($ident == 'm'){
            return "\\App\\Models\\Chanjet\\" . $name;
        }
    }
    /**
     *  数据总计
     *  @param array $field 需要合计字段
     *  @param array $whereField 过滤条件字段
    */
    public function fieldTotal($data = [],$fields =[],$whereFields = []){
        $res = [];
        foreach ($data as $key=>$val){
            foreach ($val as $key2 =>$val2){
                $valid_row = true;
                if(!empty($whereFields)){
                    foreach ($whereFields as $field){
                        if(empty($val[$field])){
                            $valid_row = false;
                            break;
                        }
                    }
                }
                if(!$valid_row){
                    continue;
                }else{
                    foreach($fields as $val3){
                        if($val3 == $key2){
                            if(isset($res[$val3])){
                                $res[$val3] = bcadd($res[$val3],$val2,3);
                            }else{
                                $res[$val3] = $val2;
                            }
                        }
                    }
                }
            }
        }
        /****
         *  增加逻辑检查，统计字段结果是否有值，不存在 给默认值
         *
        */
        if(isset($fields)){
            foreach($fields as $field){
                if(!isset($res[$field])){
                    if(strpos($field,'quantity') !== false){
                        $res[$field] = 0.0000;
                    }else if(strpos($field,'amount') !== false){
                        $res[$field] = 0.00;
                    }else{
                        $res[$field] = 0.00;
                    }
                }
            }
        }
        return $res;
    }
    /***
     *  应付明细统计
     *    单据类型 (总余额-非期初总余额+应付-已付)。
     *
     *  应收明细统计
     *
    */
    public function specialFieldTotal($data = [],$fields =[],$whereFields = [],$voucher_type = 'TplusPaymentDetail'){
        if($voucher_type == 'TplusPaymentDetail'){
            $res = $this->fieldTotal($data,$fields,$whereFields);
            //最后一个字段,balance 需要重新计算
            $decr_balance = 0;
            $incr_should_payment = 0;
            $decr_has_payment = 0;
            foreach ($data as $item){
                if($item['voucher_type'] != '期初余额'){
                    $decr_balance = bcadd($decr_balance,$item['balance']);
                    $incr_should_payment = bcadd($incr_should_payment,$item['should_payment']);
                    $decr_has_payment = bcadd($decr_has_payment,$item['has_payment']);
                }
            }
            $new_balance = bcsub($res['balance'],$decr_balance);
            $new_balance = bcadd($new_balance,$incr_should_payment);
            $new_balance = bcsub($new_balance,$decr_has_payment);
            $res['balance'] = $new_balance;
            return $res;
        }
        if($voucher_type == 'TplusReceiveDetail'){
            $res = $this->fieldTotal($data,$fields,$whereFields);
            //最后一个字段,balance 需要重新计算
            $decr_balance = 0;
            $incr_should_charged = 0;
            $decr_has_charged = 0;
            foreach ($data as $item){
                if($item['voucher_type'] != '期初余额'){
                    $decr_balance = bcadd($decr_balance,$item['balance']);
                    $incr_should_charged = bcadd($incr_should_charged,$item['should_charged']);
                    $decr_has_charged = bcadd($decr_has_charged,$item['has_charged']);
                }
            }
            $new_balance = bcsub($res['balance'],$decr_balance);
            $new_balance = bcadd($new_balance,$incr_should_charged);
            $new_balance = bcsub($new_balance,$decr_has_charged);
            $res['balance'] = $new_balance;
            return $res;
        }
    }

    /****
     *   T+ 报表请求，全部使用 Y-m-d格式
     *
     *
    */
    public function getTplusFormatDate($time = ''){
        if(isTimestamp($time)){//时间戳
            return date('Y-m-d',$time);
        }else{
            $time = strtotime($time);
            return date('Y-m-d',$time);
        }
    }
}
